package com.vertx.starter.service.impl;

import com.vertx.starter.Configure;
import com.vertx.starter.UserVo;
import com.vertx.starter.service.UserService;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.log4j.Log4j2;

import java.util.List;

@Log4j2
public class UserServiceImpl implements UserService {

    @Override
    public void list(RoutingContext ctx) {
        log.info("===> get all users");

        Configure.getInstance().daoManager.getPlayerDao().quertConfigList("select * from user", UserVo.class, o -> {
            List<UserVo> list = o.result();
            ctx.json(list);
        });
    }

    @Override
    public void add(RoutingContext ctx) {
        UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class);
        log.info("===> save user: {}", userVo);

        String sqlTmpl = "insert into user ( name ,mail,age ) value ('%s', '%s', %d)";
        String sql = String.format(sqlTmpl, userVo.getName(), userVo.getMail(), userVo.getAge());

        log.info("查询语句：{}", sql);

        Configure.getInstance().daoManager.getPlayerDao().quertConfigList(sql, UserVo.class, o -> {
            List<UserVo> list = o.result();
            ctx.json(list);
        });


    }

    @Override
    public void delete(RoutingContext ctx) {
        Long userId = Long.valueOf(ctx.pathParam("userId"));
        log.info("===> delete user: {}", userId);
        String sqlTmpl = "delete from user where id = %d";
        String sql = String.format(sqlTmpl, userId);
        log.info("查询语句：{}", sql);
        Configure.getInstance().daoManager.getPlayerDao().quertConfigList(sql, UserVo.class, o -> {
            List<UserVo> list = o.result();
            ctx.json(list);
        });
    }

    @Override
    public void get(RoutingContext ctx) {
        Long userId = Long.valueOf(ctx.pathParam("userId"));
        log.info("===> detail user: {}", userId);
        String sqlTmpl = "select * from user where id = %d";
        String sql = String.format(sqlTmpl, userId);
        log.info("查询语句：{}", sql);
        Configure.getInstance().daoManager.getPlayerDao().quertConfigList(sql, UserVo.class, o -> {
            List<UserVo> list = o.result();
            ctx.json(list);
        });
    }

    @Override
    public void update(RoutingContext ctx) {
        UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class);
        log.info("===> update user: {}", userVo);
        String sqlTmpl = "update user set name = '%s' , mail = '%s' , age = '%d' where id = %d";
        String sql = String.format(sqlTmpl, userVo.getName(), userVo.getMail(), userVo.getAge(), userVo.getId());
        log.info("查询语句：{}", sql);
        Configure.getInstance().daoManager.getPlayerDao().quertConfigList(sql, UserVo.class, o -> {
            List<UserVo> list = o.result();
            ctx.json(list);
        });
    }
}
